import UIKit

import Vision
import VisionKit
var textRecognitionRequest = VNRecognizeTextRequest()

textRecognitionRequest = VNRecognizeTextRequest(completionHandler: { (request, error) in
    if let error = error {
        print("ERROR: \(error)")
        return
    }
    guard let results = request.results, results.count > 0 else {
        print("No text found")
        return
    }
//
//    for result in results {
//        if let observation = result as? VNRecognizedTextObservation {
//            guard let text = observation.topCandidates(1).first else {
//                return
//            }
//            print(text.string)
//            print(text.confidence)
//
//
//        }
//    }
    
    let confidences: [Float] = results.compactMap { observation in
        guard let o = observation as?  VNRecognizedTextObservation,let topCandidate = o.topCandidates(1).first else { return nil }
        return topCandidate.confidence
    }
    
    let aver = confidences.reduce(0, +) / Float(confidences.count)
    print(aver)
})

textRecognitionRequest.recognitionLevel = .accurate
textRecognitionRequest.usesLanguageCorrection = true
textRecognitionRequest.recognitionLanguages = ["zh-Hans"]

func processImage(image: UIImage) {
    guard let cgImage = image.cgImage else {
        print("Failed to get cgimage from input image")
        return
    }
    
    let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
    do {
        try handler.perform([textRecognitionRequest])
    } catch {
        print(error)
    }
}

let image = UIImage(named: "3")!
processImage(image:image)
